// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

import HardModePlayer from "./HardModePlayer";
import Hp from "./Hp";
import ResultDialog from "./ResultDialog";
import Score from "./Score";

const {ccclass, property} = cc._decorator;

@ccclass
export default class HardModeGame extends cc.Component {

    static inst: HardModeGame = null;

    @property({displayName: "生成敌机间隔"})
    createEnemyInternal: number = 0;

    @property({displayName:"背景音乐", type: cc.AudioClip})
    bgmAudio: cc.AudioClip = null;

    bgmAudioID: number = 0;

    // @property({displayName: "敌机速度"})
    // enemySpeed: number = 0;

    // 子弹Prefab
    @property(cc.Prefab)
    bulletPrefab: cc.Prefab = null;

    // 子弹对象池
    bulletPool: cc.NodePool = new cc.NodePool();
    
   // 子弹Prefab
    @property(cc.Prefab)
    enemyBulletPrefab: cc.Prefab = null;

    // 子弹对象池
    enemyBulletPool: cc.NodePool = new cc.NodePool();
    
    // 敌机Prefab
    @property(cc.Prefab)
    enemyPrefab: cc.Prefab = null;
        
    // 敌机对象池
    enemyPool: cc.NodePool = new cc.NodePool();

    canvas: cc.Node = null;

    // 结果提示框
    resultDlg: ResultDialog = null;

    playing: boolean = false;

    stopOrGoOnBtn : cc.Label = null;
    
    scoreData = {key: 'score', value: '0'};

    // LIFE-CYCLE CALLBACKS:

    onLoad () {

        HardModeGame.inst = this;

        this.canvas = cc.find('Canvas');
        this.resultDlg = cc.find('Canvas/结果提示框').getComponent(ResultDialog);

        this.stopOrGoOnBtn = cc.find('Canvas/暂停').getComponent(cc.Label);

        let manager = cc.director.getCollisionManager();
        manager.enabled = true;
    }

    start () {

    }

    startHardModeGame() {

        this.playing = true;

        // 创建目标
        this.schedule(this.onCreatingEnemy, this.createEnemyInternal, cc.macro.REPEAT_FOREVER, 0.1);

        HardModePlayer.inst.healthPoint = 50;

        // 重置Hp
        Hp.i.updateHp(HardModePlayer.inst.healthPoint);

        // 重置得分
        Score.i.clearScore();

        if (this.bgmAudio != null) {

            this.bgmAudioID = cc.audioEngine.playMusic(this.bgmAudio, true);
        }
    }

    createEnemy() {

        let node = this.enemyPool.get();

        if (node == null) {

            node = cc.instantiate(this.enemyPrefab);
        }

        return node;
    }

    destroyEnemy(node: cc.Node) {
        
        this.enemyPool.put(node);
    }

    createBullet() {

        let node = this.bulletPool.get();

        if(node == null) {

            node = cc.instantiate(this.bulletPrefab);
        }

        return node;
    }

    destroyBullet(node: cc.Node) {
        
        this.bulletPool.put(node);
    }

    createEnemyBullet() {

        let node = this.enemyBulletPool.get();

        if(node == null) {

            node = cc.instantiate(this.enemyBulletPrefab);
        }

        return node;
    }

    destroyEnemyBullet(node: cc.Node) {

        this.enemyBulletPool.put(node);
    }

    // 定时生成敌机
    onCreatingEnemy() {
        
        // 每排最少生成1个敌机, 最多生成4个
        // Math.random()生成0.0 ~ 1.0的浮点数
        // Math.floor()取整
        let index: number = 0;
        index = Math.floor(Math.random() * 4 + 1);

        let enemyNode: cc.Node = this.createEnemy();
        enemyNode.parent = this.canvas;

        let w = this.canvas.width;
        let h = this.canvas.height;
        let unit = w / 4;

        enemyNode.x = unit * index - w/2 + w/8;
        enemyNode.y = (h/2) -250;

        cc.log("创建Enemy, X index:" + index, " X坐标: ",enemyNode.x, "Y坐标: ", enemyNode.y);
    }

    hardGameOver() {

        cc.log('游戏结束...');

        this.playing = false;

        // 关闭定时器, 不再生成敌机
        this.unschedule(this.onCreatingEnemy);

        // 清理屏幕上的节点
        this.clearScreen();

        // 存储得分
        let curScore = Score.i.getScore();
        
/*        let Value = cc.sys.localStorage.getItem("scoreData");
        let data = JSON.parse(Value);
        
        cc.log(data);

        if(curScore >= data.value) {

            cc.log("保存最高得分...");

            this.scoreData.value = curScore.toString();

            let storeStr = JSON.stringify(this.scoreData);
            cc.sys.localStorage.setItem('scoreData' ,storeStr);
        }*/

        // 显示结果提示框
        this.resultDlg.show();

        if (this.bgmAudio != null) {

            cc.audioEngine.stop(this.bgmAudioID);
        }
    }

    clearScreen() {

        // 获取Canvas下的所有子节点
        let nodes: cc.Node[] = this.canvas.children;

        //删除的是数组, 删除一个后, 节点索引会发生变化, 所以要倒着删除
        for (let i = nodes.length - 1; i >= 0; i--) {
            
            let node = nodes[i];

            if (node.name == '玩家子弹') {

                this.destroyBullet(node);
            }
            else if (node.name == '敌机') {

                this.destroyEnemy(node);
            }
            else if (node.name == '敌机子弹') {

                this.destroyEnemyBullet(node);
            }
        }
    }

    stopOrGoOn() {

        if (this.playing == true) {

            this.playing = false;

            this.stopOrGoOnBtn.string = "继续";

            // 关闭定时器, 不再生成Target
            this.unschedule(this.onCreatingEnemy);

            // 清理屏幕上的节点
            this.clearScreen();

            if (this.bgmAudio != null) {

                cc.audioEngine.stop(this.bgmAudioID);
            }
        }
        else if (this.playing == false) {

            this.playing = true;

            this.stopOrGoOnBtn.string = "暂停";

            // 创建目标
            this.schedule(this.onCreatingEnemy, this.createEnemyInternal, cc.macro.REPEAT_FOREVER, 0.1);

            if (this.bgmAudio != null) {

                this.bgmAudioID = cc.audioEngine.playMusic(this.bgmAudio, true);
            }
        }
        
    }

    backToMainScene() {

        cc.director.loadScene('MainScene');
    }

    // update (dt) {}
}
